<?php
/**
 * Created by PhpStorm.
 * User: mww
 * Date: 2018/9/29
 * Time: 15:37
 */
namespace app\admin\controller;
use think\Db;
use think\Request;
class Ordertuips extends Base
{
    protected $t_names = ['','夏季套装','秋季套装','礼服套装','冬季套装','西服套装'];
    /**
     * 售后订单数据
     */
    public function index(){
        if(request()->isAjax ()){
            extract(input());
            $map = [];
            $map['tui.is_delete'] = 0;
            $map['tui.tui_type'] = 3;
            if(isset($n_title)&&$n_title!="")
            {
                $map['tui.order_erp_wl_no|o.order_no|tui.express_no'] = ['like',"%" . $n_title . "%"];
            }

            if(isset($status) && $status){
                $map['tui.status'] = $status;
            }
            if(isset($is_send) && $is_send >= 0 && $is_send != ''){
                $map['tui.is_send'] = $is_send;
            }
            if(isset($school) && $school){
                $map['s.school_erp'] = $school;
            }
            if(isset($year) && $year){
                $map['o.order_erp_year'] = $year;
            }
            if(isset($back) && $back){
                if($back == 1){
//                    $map['tui.express_no'] = [[['=',null],['=','']],'OR'];
                    $map['tui.express_no'] = '';
                }else{
                    $map['tui.express_no'] = ['<>',''];
                }
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $field = 'tui.*,o.order_no order_oldno,o.order_erp_year,s.school_name,count(*) allnum';
            $field .= ',uson_username,uson_parent_phone';
            $count = Db::table('up_self_order_tui')->alias('tui')
                ->join('up_self_order o','tui.order_id=o.order_id','LEFT')
                ->join('up_school s','o.order_school=s.school_erp','LEFT')
                ->join('up_u_user_son us','o.order_user_son_id=us.uson_id','LEFT')
                ->group('order_erp_wl_no,tui_tg_type')
                ->where($map)
                ->count();// 获取总条数
            $lists = Db::table('up_self_order_tui')->alias('tui')
                ->join('up_self_order o','tui.order_id=o.order_id','LEFT')
                ->join('up_school s','o.order_school=s.school_erp','LEFT')
                ->join('up_u_user_son us','o.order_user_son_id=us.uson_id','LEFT')
                ->group('order_erp_wl_no,tui_tg_type')
                ->where($map)
                ->order('status ASC,is_send ASC,created_at ASC')
                ->page($Nowpage,$limits)
                ->field($field)
                ->select();
            if($lists){
                $t_names = $this->t_names;
                foreach ($lists as $k => $v){
                    $lists[$k]['name'] = $t_names[$v['tui_tg_type']];
                    if($v['pic_list']){
                        $data[$k]['pic_list'] = explode(',',$v['pic_list']);
                    }
                }
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $schools = Db::table('up_school')
            ->field('school_id,school_erp,school_name')
            ->select();
        $this->assign('schools',$schools);
        return $this->fetch('ordertuips/index');
    }

    /**
     * 同意或拒绝
     */
    public function orderYesNo(){
        extract(input());
        if(Request::instance()->isPost()){
            extract(input());
            $today = date('Y-m-d H:i:s');
            $tui = Db::table('up_self_order_tui')
                ->where('tui_id',$tui_id)
                ->field('status,order_id,order_detail_id,tui_tg_type,user_id,order_erp_wl_no')
                ->find();
            if($tui['status'] != 1){
                return json(['code'=>100,'msg'=>'只有待处理的售后订单才可以审核']);
            }
            $param  = [
                'status' => $status,
                'status_time'=>$today,
                'merchant_remark'=>$merchant_remark,
            ];
            Db::startTrans();
            try{
                Db::table('up_self_order_tui')
                    ->where('order_erp_wl_no',$tui['order_erp_wl_no'])
                    ->where('order_id',$tui['order_id'])
                    ->where('tui_tg_type',$tui['tui_tg_type'])
                    ->update($param);
                if($status == 3){
                    Db::table('up_self_order_detail')
                        ->where('order_id',$tui['order_id'])
                        ->where('tg_type',$tui['tui_tg_type'])
                        ->setField('refund_status',2);
                }
                Db::commit();
                if($status == 2){
                    try{
                        $this->Jpush(1, $tui['user_id'], '换货同意通知', ['n_id' => $tui['order_id'],'type' => 3,'n_type' => 4]);
                    }catch(\Exception $e){

                    }
                    $title = '换货同意通知';
                    $content = '由客服检验换货没有问题，请及时回寄！';
                    allInNotice($title,$content,4,$tui['user_id'],$tui['order_id'],3);
                }
                return json(['code'=>200,'msg'=>'成功']);
            }catch (\Exception $e) {
                Db::rollback();
                return json(['code'=>100,'msg'=>'失败']);
            }
        }
        $tui = Db::table('up_self_order_tui')
            ->where('tui_id',$tui_id)
            ->field('status,order_id,order_erp_wl_no')
            ->find();
        if($tui['status'] != 1){
            return '只有待处理的售后订单才可以审核！';
            exit();
        }
        return $this->fetch('ordertuips/orderyesno',['tui_id'=>$tui_id]);
    }
    /**
     * 确认收货
     */
    public function sureGet(){
        extract(input());
        if(Request::instance()->isPost()){
            extract(input());
            $today = date('Y-m-d H:i:s');
            $tui = Db::table('up_self_order_tui')
                ->where('tui_id',$tui_id)
                ->field('status,order_id,order_detail_id,user_id,tui_type,order_erp_wl_no,tui_sure_get')
                ->find();
            if($tui['status'] != 2 || $tui['tui_sure_get'] != 1){
                return json(['code'=>100,'msg'=>'只有待处理且未确认收货的售后订单才可以操作']);
            }
            Db::startTrans();
            try{
                if(empty($fahuo)){
                    Db::table('up_self_order_tui')
                        ->where('order_erp_wl_no',$tui['order_erp_wl_no'])
                        ->setField('tui_sure_get',3);
                }else{
                    $tuids = implode($fahuo,',');
                    Db::table('up_self_order_tui')
                        ->where('tui_id','in',$tuids)
                        ->setField('tui_sure_get',2);
                    Db::table('up_self_order_tui')
                        ->where('order_erp_wl_no',$tui['order_erp_wl_no'])
                        ->where('tui_id','not in',$tuids)
                        ->setField('tui_sure_get',3);
                }
                Db::commit();
                return json(['code'=>200,'msg'=>'操作成功']);
            }catch (\Exception $e) {
                Db::rollback();
                return json(['code'=>100,'msg'=>'失败']);
            }
        }
        $data = Db::table('up_self_order_tui')
            ->where('tui_id',$tui_id)
            ->field('status,order_id,tui_user_son_id,order_erp_wl_no,tui_sure_get')
            ->find();
        if($data['status'] != 2 || $data['tui_sure_get'] != 1){
            return '只有待处理且未确认收货的售后订单才可以操作！';
            exit();
        }
        $order = Db::table('up_self_order')
            ->where('order_id',$data['order_id'])
            ->find();
        //----------------------------------------------
        $field = 'tui_id,num,unit_price,goods_info,good_id,good_name,good_thumb,attr_id,type,status,is_send,good_coding';
        $details = Db::table('up_self_order_tui')->alias('o')
            ->join('up_self_order_detail od','o.order_detail_id=od.detail_id','LEFT')
            ->join("up_goods g",'od.goods_id=g.good_id','LEFT')
            ->where('order_erp_wl_no',$data['order_erp_wl_no'])
            ->field($field)
            ->select();
        return $this->fetch('ordertuips/sureget',['data'=>$order,'details'=>$details,'tui_id'=>$tui_id]);
    }
    /**
     * 发货
     */
    public function orderSend(){
        extract(input());
        if(Request::instance()->isPost()){
            extract(input());
            $today = date('Y-m-d H:i:s');
            $tui = Db::table('up_self_order_tui')
                ->where('tui_id',$tui_id)
                ->field('order_detail_id,tui_tg_type,order_erp_wl_no,status,order_id,is_send')
                ->find();
            $param  = [
                'is_send'=>1,
                'send_time'=>$today,
                'merchant_express'=>trim($merchant_express,' '),
                'merchant_express_no'=>trim($merchant_express_no,' '),
            ];
            Db::startTrans();
            try{
                //---------------------------------------
                $this->changeOrder($tui['order_id']);
                //---------------------------------------
                Db::table('up_self_order_tui')
                    ->where('order_erp_wl_no',$tui['order_erp_wl_no'])
                    ->where('order_id',$tui['order_id'])
                    ->where('tui_tg_type',$tui['tui_tg_type'])
                    ->update($param);
                if($tui['is_send'] == 0){
                    Db::table('up_self_order_detail')
                        ->where('order_id',$tui['order_id'])
                        ->where('tg_type',$tui['tui_tg_type'])
                        ->setField('refund_status',2);
                }
                Db::commit();
                return json(['code'=>200,'msg'=>'成功']);
            }catch (\Exception $e) {
                Db::rollback();
                return json(['code'=>100,'msg'=>'失败']);
            }
        }
        $tui = Db::table('up_self_order_tui')
            ->where('tui_id',$tui_id)
            ->field('tui_id,merchant_express,merchant_express_no,order_id')
            ->find();
        $order = Db::table('up_self_order')
            ->where('order_id',$tui['order_id'])
            ->field('name,mobile,address')
            ->find();
        return $this->fetch('ordertuips/ordersend',['data'=>$order,'tui'=>$tui]);
    }


    /**
     * 订单详情
     */
    public function orderInfo(){
        $tui_id = input('tui_id');
        $field = 'tui.*,o.order_no order_oldno,o.order_erp_year,s.school_name,count(*) allnum';
        $field .= ',uson_username,uson_parent_phone';
        $data = Db::table('up_self_order_tui')->alias('tui')
            ->join('up_self_order o','tui.order_id=o.order_id','LEFT')
            ->join('up_school s','o.order_school=s.school_erp','LEFT')
            ->join('up_u_user_son us','o.order_user_son_id=us.uson_id','LEFT')
            ->where('tui_id',$tui_id)
            ->field($field)
            ->find();
        if($data['pic_list']){
            $data['pic_list'] = explode(',',$data['pic_list']);
        }
        $field = 'num,unit_price,goods_info,good_id,good_name,good_thumb,attr_id,type,status,is_send,good_coding,erp_new_size,tui_sure_get';
        $details = Db::table('up_self_order_tui')->alias('o')
            ->join('up_self_order_detail od','o.order_detail_id=od.detail_id','LEFT')
            ->join("up_goods g",'od.goods_id=g.good_id','LEFT')
            ->where('order_erp_wl_no',$data['order_erp_wl_no'])
            ->field($field)
            ->select();
        $data['goods'] = $details;
        $t_names = $this->t_names;
        return $this->fetch('ordertuips/orderinfo',['data'=>$data,'t_names'=>$t_names,'rows'=>count($details)]);
    }
    /**
     * 导入物流Excel
     * @return mixed
     */
    public function excelIn(){
        set_time_limit(0);
        if(request()->file('file')){
            $file = request()->file('file');
            $info  = $file->getInfo();
            $file_path = $info['tmp_name'];
            //取出文件后缀
            $file_type = explode(".",$info['name']);
            $file_type = end($file_type);
            vendor("PHPExcel.PHPExcel.IOFactory");
            if( $file_type == 'xls' ){
                $inputFileType = 'Excel5';    //这个是读 xls的
            }else{
                $inputFileType = 'Excel2007';//这个是计xlsx的
            }
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($file_path);
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
//            print_r($highestRow);die;
            $time = date('Y-m-d H:i:s');
            $data = [];
            Db::startTrans();
            try {
                for ($i=2;$i<=$highestRow;$i++) {
                    $a = $objPHPExcel->getActiveSheet ()->getCell ("A" . $i)->getValue (); //
                    $b = $objPHPExcel->getActiveSheet ()->getCell ("B" . $i)->getValue (); //
                    $c = $objPHPExcel->getActiveSheet ()->getCell ("C" . $i)->getValue (); //
                    $d = $objPHPExcel->getActiveSheet ()->getCell ("D" . $i)->getValue (); //
                    if($a != '' && $b != '' && $d != ''){
                        $tui = Db::table('up_self_order_tui')
                            ->where('order_erp_wl_no',$a)
                            ->field('order_detail_id,tui_tg_type,status,order_id,is_send')
                            ->find();
                        $param  = [
                            'is_send'=>1,
                            'send_time'=>$time,
                            'merchant_express'=>trim($c,' '),
                            'merchant_express_no'=>trim($d,' '),
                        ];
                        //---------------------------------------
                        $this->changeOrder($tui['order_id']);
                        //---------------------------------------
                        Db::table('up_self_order_tui')
                            ->where('order_erp_wl_no',$a)
                            ->where('order_id',$tui['order_id'])
                            ->where('tui_tg_type',$tui['tui_tg_type'])
                            ->update($param);
                        if($tui['is_send'] == 0){
                            Db::table('up_self_order_detail')
                                ->where('order_id',$tui['order_id'])
                                ->where('tg_type',$tui['tui_tg_type'])
                                ->setField('refund_status',2);
                        }
                    }
                }
                Db::commit();
                echo '/admin/ordertuips/index';
            } catch (\Exception $e) {
                Db::rollback();
                echo '/admin/ordertuips/excelIn';
            }
        }
        return $this->fetch('ordertuips/excelin');
    }
    public function excelOut()
    {
        set_time_limit(0);//防止超时
        extract(input());
        $map = [];
        $map['tui.is_delete'] = 0;
        $map['tui.tui_type'] = 3;
        if(isset($n_title)&&$n_title!="")
        {
            $map['tui.order_erp_wl_no|o.order_no|tui.express_no'] = ['like',"%" . $n_title . "%"];
        }

        if(isset($status) && $status){
            $map['tui.status'] = $status;
        }
        if(isset($is_send) && $is_send >= 0){
            $map['tui.is_send'] = $is_send;
        }
        if(isset($school) && $school){
            $map['s.school_erp'] = $school;
        }
        if(isset($year) && $year){
            $map['o.order_erp_year'] = $year;
        }
        if(isset($back) && $back){
            if($back == 1){
//                    $map['tui.express_no'] = [[['=',null],['=','']],'OR'];
                $map['tui.express_no'] = '';
            }else{
                $map['tui.express_no'] = ['<>',''];
            }
        }
        $field = [
            'tui.order_erp_wl_no','o.order_no','school_name', 'tui_tg_type','count(*) tui_tg_num',
            'o.name','user_phone','tui.created_at','tui.type','tui.tui_type',
            'tui.remark','tui.express','tui.express_no','tui.status','tui.is_send',
            'tui.status_time'
        ];
        $data = Db::table('up_self_order_tui')->alias('tui')
            ->join('up_self_order o','tui.order_id=o.order_id','LEFT')
            ->join('up_school s','o.order_school=s.school_erp','LEFT')
            ->join('up_u_user u','o.user_id=u.user_id','LEFT')
            ->group('order_erp_wl_no,tui_tg_type')
            ->where($map)
            ->order('status ASC,is_send ASC,created_at ASC')
            ->field($field)
            ->select();
        if($data){
            $cellname = [
                '退货单号', '原订单号', '学校名字', '套装名称', '套装数量',
                '用户昵称', '用户电话', '创建时间', '售后类型', '订单类型',
                '备注', '退货物流', '退货单号', '售后状态', '售后进度',
                '同意时间'
            ];
            $status = ['tui_tg_type','type','tui_type','status','is_send'];
            $values = [
                'tui_tg_type' => [1 => '夏季套装',2 => '秋季套装',3 => '礼服套装',4 => '冬季套装',5 => '西服套装'],
                'type' => [1 => '换货',2 => '退货'],
                'tui_type' => [1 => '自营订单',2 => '增补订单',3 => '统购订单'],
                'status' => [1 => '待处理',2 => '同意',3 => '拒绝'],
                'is_send' => [0 => '未发货',1 => '已发货']
            ];
            $res = exportExcel('tuiorder',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }
    public function excelOutAll()
    {
        set_time_limit(0);//防止超时
        extract(input());
        $map = [];
        $map['tui.is_delete'] = 0;
        $map['tui.tui_type'] = 3;
        if(isset($n_title)&&$n_title!="")
        {
            $map['tui.order_erp_wl_no|o.order_no|tui.express_no'] = ['like',"%" . $n_title . "%"];
        }

        if(isset($status) && $status){
            $map['tui.status'] = $status;
        }
        if(isset($is_send) && $is_send >= 0){
            $map['tui.is_send'] = $is_send;
        }
        if(isset($school) && $school){
            $map['s.school_erp'] = $school;
        }
        if(isset($year) && $year){
            $map['o.order_erp_year'] = $year;
        }
        if(isset($back) && $back){
            if($back == 1){
//                    $map['tui.express_no'] = [[['=',null],['=','']],'OR'];
                $map['tui.express_no'] = '';
            }else{
                $map['tui.express_no'] = ['<>',''];
            }
        }
        $field = [
            'tui.order_erp_wl_no','o.order_no','school_name', 'g.good_name','od.unit_price',
            'od.num','od.attr_id','tui.erp_new_size','g.good_color','g.good_coding',
            'o.name','user_phone','tui.created_at','tui.type','tui.tui_type',
            'tui.remark','tui.express','tui.express_no','tui.status','tui.is_send',
            'tui.status_time'
        ];
        $data = Db::table('up_self_order_tui')->alias('tui')
            ->join('up_self_order o','tui.order_id=o.order_id','LEFT')
            ->join('up_school s','o.order_school=s.school_erp','LEFT')
            ->join('up_u_user u','o.user_id=u.user_id','LEFT')
            ->join('up_self_order_detail od','tui.order_detail_id=od.detail_id','LEFT')
            ->join("up_goods g",'od.goods_id=g.good_id','LEFT')
            ->where($map)
            ->order('status ASC,is_send ASC,created_at ASC')
            ->field($field)
            ->select();
        if($data){
            $cellname = [
                '退货单号', '原订单号', '学校名字', '商品名称', '商品单价',
                '数量', '原尺码', '调换尺码', '产品信息', '唯一编码',
                '用户昵称', '用户电话', '创建时间', '售后类型', '订单类型',
                '备注', '退货物流', '退货单号', '售后状态', '售后进度',
                '同意时间'
            ];
            $status = ['type','tui_type','status','is_send'];
            $values = [
                'type' => [1 => '换货',2 => '退货'],
                'tui_type' => [1 => '自营订单',2 => '增补订单',3 => '统购订单'],
                'status' => [1 => '待处理',2 => '同意',3 => '拒绝'],
                'is_send' => [0 => '未发货',1 => '已发货']
            ];
            $res = exportExcel('tuiorderdetail',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }
}